package com.yuanda.erp9.syn.service.erp9.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yuanda.erp9.syn.contant.RateCalculateConstants;
import com.yuanda.erp9.syn.entity.CmsBrandsTempEntity;
import com.yuanda.erp9.syn.entity.CmsGoodsEntity;
import com.yuanda.erp9.syn.entity.CmsGoodsInformationEntity;
import com.yuanda.erp9.syn.entity.CmsPricesEntity;
import com.yuanda.erp9.syn.enums.CachePrefixEnum;
import com.yuanda.erp9.syn.enums.DeliveryAreaEnum;
import com.yuanda.erp9.syn.enums.SourceEnum;
import com.yuanda.erp9.syn.execule.thread.Master;
import com.yuanda.erp9.syn.helper.AventAbacusExcelHelper;
import com.yuanda.erp9.syn.helper.RetryOperateLogHelper;
import com.yuanda.erp9.syn.poi.AventAbacusExcelData;
import com.yuanda.erp9.syn.pojo.CmsGoodsPojo;
import com.yuanda.erp9.syn.service.erp9.AventAbacusExcelService;
import com.yuanda.erp9.syn.service.erp9.CmsTopicUpdateSumLogService;
import com.yuanda.erp9.syn.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;

/**
 * @ClassName FutureExcelServiceImpl
 * @Description
 * @Date 2022/12/1
 * @Author myq
 */
@Slf4j
@Service
public class AventAbacusExcelServiceImpl implements AventAbacusExcelService {

    @Autowired
    private AventAbacusExcelHelper aventAbacusExcelHelper;

    @Autowired
    private RetryOperateLogHelper retryOperateLogHelper;

    @Autowired
    private CmsTopicUpdateSumLogService cmsTopicUpdateSumLogService;


    private final String US_CODE = "US000006971";
    private final String SUPPLIER = "Avnet-Hot";
    private int index = 1;


    /**
     * @Description: 解析excel
     * @Params:
     * @Return:
     * @Author: Mr.myq
     * @Date: 2022/12/116:33
     */
    @Override
    public void parse(String filePath, Long pk) {
        Integer supplierId = CacheUtil.init(CachePrefixEnum.SUPPLIERS.getKey()).get(SUPPLIER);
        AtomicInteger sum = new AtomicInteger(0);
        Master<CmsGoodsPojo> objectMaster = new Master<>(supplierId, "avhabacus", SourceEnum.EMAIL.getCode());
        try {
            EasyExcelUtils.readExcel(filePath, AventAbacusExcelData.class, new Consumer<AventAbacusExcelData>() {
                @Override
                public void accept(AventAbacusExcelData aventAbacusExcelData) {
                    try {
                        sum.incrementAndGet();
                        // 包装类
                        CmsGoodsPojo cmsGoodsPojo = new CmsGoodsPojo();
                        //商品类
                        CmsGoodsEntity cmsGoodsEntity = new CmsGoodsEntity();
                        cmsGoodsEntity.setAdminid(0);
                        cmsGoodsEntity.setTenantsid(0);
                        cmsGoodsEntity.setClassifyid(0);
                        cmsGoodsEntity.setImg("");
                        cmsGoodsEntity.setType(0);
                        cmsGoodsEntity.setStatus(1);
                        cmsGoodsEntity.setStatusMsg("");
                        cmsGoodsEntity.setDataType(1);
                        cmsGoodsEntity.setModel(aventAbacusExcelData.getArticle().trim());
                        CmsBrandsTempEntity cmsBrandsTempEntity = new CmsBrandsTempEntity();
                        cmsBrandsTempEntity.setTag(0);
                        cmsBrandsTempEntity.setName(aventAbacusExcelData.getManuf());
                        Integer brandId = CacheUtil.init(CachePrefixEnum.BRAND.getKey()).insertAndGet(cmsBrandsTempEntity);
                        cmsGoodsEntity.setBrand(brandId);
                        cmsGoodsEntity.setBrandName(aventAbacusExcelData.getManuf());

                        cmsGoodsEntity.setSupplier(supplierId);
                        cmsGoodsEntity.setSplName(SUPPLIER);
                        String sign = String.join("-", "hisp", aventAbacusExcelData.getArticle(), String.valueOf(index++));
                        String incodes = EasyExcelUtils.getIncodes(sign, US_CODE, supplierId);
                        cmsGoodsEntity.setIncodes(incodes);
                        cmsGoodsEntity.setGoodid(incodes);
                        cmsGoodsEntity.setIsSampleApply(0);
                        cmsGoodsEntity.setBatch("");
                        cmsGoodsEntity.setOriginalPrice(new BigDecimal("0.00"));
                        cmsGoodsEntity.setPurchasePrice(new BigDecimal("0.00"));
                        int count = Integer.parseInt(NumberUtils.isNumber(aventAbacusExcelData.getStock()) ? aventAbacusExcelData.getStock() : "0");
                        cmsGoodsEntity.setRepertory(count);
                        cmsGoodsEntity.setRepertoryArea("德国");
                        cmsGoodsEntity.setPublish(1);
                        cmsGoodsEntity.setDescribe(aventAbacusExcelData.getTechDescr());
                        cmsGoodsEntity.setFiles("");
                        cmsGoodsEntity.setPayType(0);
                        // 最小起订量
                        int moq = Integer.parseInt(NumberUtils.isNumber(aventAbacusExcelData.getMoq()) ? aventAbacusExcelData.getMoq() : "0");
                        int packQty = NumberUtils.isNumber(aventAbacusExcelData.getMpq()) ? Integer.parseInt(aventAbacusExcelData.getMpq()) : 1;
                        BigDecimal price = new BigDecimal(aventAbacusExcelData.getPrice().replaceAll(",", ""));
                        if (price.multiply(new BigDecimal(moq)).intValue() >= 150) {
                            cmsGoodsEntity.setMinimumOrder((long) (moq == 0 ? 1 : moq));
                        } else {
                            int g = Math.max((new BigDecimal("150").divide(price, RoundingMode.HALF_UP).setScale(4)).intValue() + 1, packQty);
                            //整包订购
                            int i = (g / (double) packQty > g / packQty ? g / packQty + 1 : g / packQty) * packQty;
                            cmsGoodsEntity.setMinimumOrder((long) (i == 0 ? 1 : i));
                        }
                        cmsGoodsEntity.setDomesticDate(aventAbacusExcelHelper.getDelivery("domesticDate"));
                        cmsGoodsEntity.setHongkongDate(aventAbacusExcelHelper.getDelivery("hongkongDate"));
                        cmsGoodsEntity.setDeliveryArea(DeliveryAreaEnum.OTHER.getCode());
                        cmsGoodsEntity.setIncremental((long) (packQty > 0 ? packQty : 1));
                        cmsGoodsEntity.setMpq((long) packQty);
                        cmsGoodsEntity.setSource(SourceEnum.EMAIL.getCode());
                        cmsGoodsEntity.setHisp("avhabacus");
                        cmsGoodsEntity.setSales(0);
                        cmsGoodsEntity.setClick(0);
                        cmsGoodsEntity.setVisitor(0);
                        cmsGoodsEntity.setCreatedAt(DateUtils.dateToString(new Date(), DateUtils.simpleDateHms));
                        cmsGoodsEntity.setUpdatedAt(DateUtils.dateToString(new Date(), DateUtils.simpleDateHms));
                        cmsGoodsEntity.setActivityId(0);
                        cmsGoodsEntity.setContent(null);
                        //费率
                        JSONObject data = RateCalculateUtil.getRate(cmsGoodsEntity.getBrandName(), cmsGoodsEntity.getModel());
                        // 费率信息
                        JSONObject rateJsonObject = (JSONObject) data.get(RateCalculateConstants.RATE);
                        cmsGoodsEntity.setRates(rateJsonObject);
                        //关税
                        BigDecimal tariffRate = rateJsonObject.getBigDecimal(RateCalculateConstants.TARIFFRATE_FIELD);
                        //商检税
                        BigDecimal cIQprice = rateJsonObject.getBigDecimal(RateCalculateConstants.CIQPRICE_FIELD);
                        //税费计算和存储
                        if (tariffRate != null) {
                            cmsGoodsEntity.setTariffsRate(tariffRate.doubleValue());
                        }
                        if (cIQprice != null) {
                            cmsGoodsEntity.setInspectionChargesFee(cIQprice.doubleValue());
                        }
                        cmsGoodsEntity.setEmbargo(data.get(RateCalculateConstants.EMBARGO_FIELD) == null ? 0 : data.getInteger(RateCalculateConstants.EMBARGO_FIELD));
                        cmsGoodsEntity.setCcc(data.get(RateCalculateConstants.CCC_FIELD) == null ? 0 : data.getInteger(RateCalculateConstants.CCC_FIELD));
                        cmsGoodsEntity.setEccnNo(data.getString(RateCalculateConstants.ECCN_FIELD));

                        // 参数
                        cmsGoodsEntity.setParams(null);

                        // 阶梯价格
                        List<Map<String, String>> ladderPrice = aventAbacusExcelHelper.getLadderPrice(packQty, price, "USD");
                        if (!CollectionUtils.isEmpty(ladderPrice)) {
                            cmsGoodsEntity.setMinimumOrder(Math.max(Integer.parseInt(ladderPrice.get(0).get("min")), cmsGoodsEntity.getMinimumOrder()));
//                            cmsGoodsEntity.setUnitPrice(Double.parseDouble(MathUtil.divide(ladderPrice.get(0).get("price"), cmsGoodsEntity.getMinimumOrder())));
                        } else {
                            cmsGoodsEntity.setUnitPrice(0.0000);
                        }
                        cmsGoodsEntity.setPrices(JSON.toJSONString(ladderPrice));
                        cmsGoodsPojo.setCmsGoodsEntity(cmsGoodsEntity);

                        CmsGoodsInformationEntity cmsGoodsInformationEntity = new CmsGoodsInformationEntity();
                        cmsGoodsInformationEntity.setGoodid(incodes);
                        cmsGoodsInformationEntity.setEcnn(1);
                        cmsGoodsInformationEntity.setAtlas("");
                        cmsGoodsInformationEntity.setContent(aventAbacusExcelData.getTechDescr());
                        cmsGoodsInformationEntity.setActivity(0);
                        cmsGoodsInformationEntity.setEcnnnumber("");
                        cmsGoodsInformationEntity.setTariffs(0);
                        cmsGoodsInformationEntity.setTariffsrate(0);
                        cmsGoodsInformationEntity.setInspectionCharges(0);
                        cmsGoodsInformationEntity.setInspectionChargesFee(cmsGoodsEntity.getInspectionChargesFee());
                        cmsGoodsInformationEntity.setParams(null);
                        cmsGoodsInformationEntity.setCreatedAt(new Date());
                        cmsGoodsPojo.setCmsGoodsInformationEntity(cmsGoodsInformationEntity);

                        // price
                        List<CmsPricesEntity> pricesEntities = new ArrayList<>(6);
                        for (Map<String, String> m : ladderPrice) {
                            CmsPricesEntity pricesEntity = new CmsPricesEntity();
                            pricesEntity.setLadderid(0);
                            pricesEntity.setGoodid(incodes);
                            pricesEntity.setMin(Long.parseLong(m.get("min")));
                            pricesEntity.setMax(Long.parseLong(m.get("max")));
                            pricesEntity.setPrice(BigDecimal.valueOf(Double.parseDouble(m.get("price"))));
                            pricesEntity.setCurrency(Integer.parseInt(m.get("currency")));
                            pricesEntity.setPosition(Integer.parseInt(m.get("position")));
                            pricesEntity.setDiscountRate(new BigDecimal(m.get("discount_rate")));
                            pricesEntity.setDiscountPrice(new BigDecimal(m.get("discount_price")));
                            pricesEntity.setPublish(0);
                            pricesEntity.setCreatedAt(new Date());
                            pricesEntity.setUpdatedAt(new Date());
                            pricesEntities.add(pricesEntity);
                        }
                        cmsGoodsPojo.setCmsPricesEntityList(pricesEntities);
                        objectMaster.add(cmsGoodsPojo);
                    } catch (Exception e) {
                        log.warn("解析AventAbaus数据异常，将丢弃此条数据");
                        retryOperateLogHelper.add(aventAbacusExcelData, supplierId, e.toString());
                    }
                }
            });
        } finally {
            // 退出标志
            objectMaster.isBegin = false;
            cmsTopicUpdateSumLogService.insertBySum(sum.longValue(), pk);
        }

    }

}
